package net.arogarth.aws.android.manager.views;

import java.util.ArrayList;
import java.util.List;

import net.arogarth.aws.android.lib.AmazonEc2;
import net.arogarth.aws.android.lib.AwsRequestException;
import net.arogarth.aws.android.lib.AwsSettings;
import net.arogarth.aws.android.lib.models.Ec2Ebs;
import net.arogarth.aws.android.lib.models.Ec2Instance;
import net.arogarth.aws.android.manager.R;
import net.arogarth.aws.android.manager.dbmodels.AvailabilityZone;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Create and Manage the List of Elastic-Block-Storages
 * 
 * @author arogarth
 * 
 */
public class Ec2EbsList extends Activity {
	/**
	 * The ListAdapter
	 * 
	 * @author arogarth
	 * 
	 */
	public class Ec2EbsListAdapter extends BaseAdapter implements
			AdapterView.OnItemLongClickListener {

		private final List<Ec2Ebs> volumes = new ArrayList<Ec2Ebs>();
		private final List<Ec2Instance> instances = new ArrayList<Ec2Instance>();

		private Context context;

		public Ec2EbsListAdapter(Context view, ListView list) {
			this.context = view;

			list.setAdapter(this);
			list.setOnItemLongClickListener(this);

			this.loadData();
		}

		private void loadData() {
			final ProgressDialog pd = ProgressDialog.show(this.context,
					"Please wait ...", "Loading Data ...", true, false);

			final Thread t = new Thread() {
				public void run() {
					AmazonEc2 aec2 = new AmazonEc2();

					try {
						List<Ec2Ebs> _volumes = aec2.describeVolumes();

						volumes.clear();
						for (Ec2Ebs volume : _volumes) {
							volumes.add(volume);
						}

						List<Ec2Instance> _instances = aec2.descriptInstances();
						for (Ec2Instance instance : _instances)
							instances.add(instance);

						handler.sendEmptyMessage(0);
					} catch (final AwsRequestException e) {
						runOnUiThread(new Runnable() {
							public void run() {
								Toast.makeText(context, e.getMessage(),
										Toast.LENGTH_SHORT).show();
								finish();
							}
						});
					}
				}

				private Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {
						notifyDataSetChanged();
						pd.dismiss();
					}
				};
			};
			t.start();
		}

		public int getCount() {
			return this.volumes.size();
		}

		public Ec2Ebs getItem(int arg0) {
			return (Ec2Ebs) this.volumes.get(arg0);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final Ec2Ebs volume = (Ec2Ebs) getItem(position);

			final LinearLayout _ll = (LinearLayout) LayoutInflater.from(
					this.context).inflate(R.layout.ec2_ebs_list_item, parent, false);

			((TextView) _ll.findViewById(R.id.volumeId)).setText(volume
					.getVolumeId());

			if (!volume.getDevice().equals(""))
				((TextView) _ll.findViewById(R.id.tvDevice)).setText(String
						.format("%s: %s", volume.getInstanceId(),
								volume.getDevice()));

			( (TextView) _ll.findViewById(R.id.tvState) ).setText(volume.getStatus());
			( (TextView) _ll.findViewById(R.id.tvSize) ).setText(String.format("%s GB", volume.getSize() ) );
			( (TextView) _ll.findViewById(R.id.tvZone) ).setText(volume.getAvailabilityZone());
			( (TextView) _ll.findViewById(R.id.tvCreated) ).setText(volume.getCreateTime());
					
			return _ll;
		}

		/**
		 * Fired if a volume pressed long
		 */
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int position, long arg3) {
			final Ec2Ebs ebsVolume = (Ec2Ebs) this.getItem(position);

			AlertDialog.Builder builder = new AlertDialog.Builder(this.context);

			if (ebsVolume.getStatus().equalsIgnoreCase("available")) {
				CharSequence[] options = { "Attach", "Create Snapshot",
						"Delete Volume" };

				builder.setItems(options,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									final int which) {
								switch (which) {
								case 0: // Attach Volume
									onClickAttachVolume(ebsVolume);
									break;
								case 1: // Create a Snapshot
									onClickCreateSnapshot(ebsVolume);
									break;
								case 2: // Delete Volume
									onClickDeleteVolume(ebsVolume);
									break;
								}
							}
						});

			} else {
				CharSequence[] options = { "Detach", "Create Snapshot", };

				builder.setItems(options,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									final int which) {
								switch (which) {
								case 0: // Detach Volume
									onClickDetachVolume(ebsVolume);
									break;
								case 1: // Create Snapshot
									onClickCreateSnapshot(ebsVolume);
									break;
								}
							}
						});
			}

			builder.create().show();

			return true;
		}

		private void onClickAttachVolume(final Ec2Ebs ebsVolume) {
			final Dialog dlg = new Dialog(this.context);
			dlg.setContentView(R.layout.dialog_attach_volume);
			dlg.setTitle("Select Instance");

			String[] strInstaces = new String[instances.size()];
			for (int i = 0; i < instances.size(); i++) {
				strInstaces[i] = instances.get(i).getInstanceId();
			}

			ArrayAdapter<String> ad = new ArrayAdapter<String>(
					getApplicationContext(),
					android.R.layout.simple_spinner_dropdown_item, strInstaces);

			final Spinner sp = (Spinner) dlg.findViewById(R.id.spInstance);
			sp.setAdapter(ad);

			final EditText ed = (EditText) dlg.findViewById(R.id.etDevice);

			View.OnClickListener clickListener = new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					try {
						String instance = (String) sp.getSelectedItem();
						String device = ed.getText().toString();

						new AmazonEc2().attachVolume(ebsVolume.getVolumeId(),
								instance, device);
						
						dlg.dismiss();
						
						loadData();
					} catch (AwsRequestException e) {
						Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
					}
				}
			};

			((Button) dlg.findViewById(R.id.btnAttach))
					.setOnClickListener(clickListener);
			
			dlg.show();
		}

		private void onClickDetachVolume(final Ec2Ebs ebsVolume) {
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						// Yes button clicked
						try {
							new AmazonEc2().detachVolume(ebsVolume
									.getVolumeId());
						} catch (AwsRequestException e) {
						}
						
						loadData();
						
						break;

					case DialogInterface.BUTTON_NEGATIVE:
						// No button clicked
						break;
					}
				}
			};

			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setMessage("Are you sure?")
					.setPositiveButton("Yes", dialogClickListener)
					.setNegativeButton("No", dialogClickListener).show();
		}

		private void onClickCreateSnapshot(final Ec2Ebs ebsVolume) {
			try {
				new AmazonEc2().createSnapshot(ebsVolume.getVolumeId());
			} catch (AwsRequestException e) {
			}
		}

		private void onClickDeleteVolume(final Ec2Ebs ebsVolume) {
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						// Yes button clicked
						try {
							new AmazonEc2().deleteVolume(ebsVolume
									.getVolumeId());
						} catch (AwsRequestException e) {
						}
						break;

					case DialogInterface.BUTTON_NEGATIVE:
						// No button clicked
						break;
					}
				}
			};

			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setMessage("Are you sure?")
					.setPositiveButton("Yes", dialogClickListener)
					.setNegativeButton("No", dialogClickListener).show();
		}
	}

	Ec2EbsListAdapter adapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.basic_list);
		final ListView lv = (ListView) findViewById(R.id.contentlist);
		adapter = new Ec2EbsListAdapter(Ec2EbsList.this, lv);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.ebs_images, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.miAddAccount:
			showCreateVolumeDialog();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	public void showCreateVolumeDialog() {
		final Dialog dlg = new Dialog(Ec2EbsList.this);
		dlg.setContentView(R.layout.dialog_create_volume);
		dlg.setTitle("Create Volume");
		
		@SuppressWarnings("unchecked")
		List<AvailabilityZone> zones = (List<AvailabilityZone>) new AvailabilityZone()
			.list(String.format("region = '%s'", AwsSettings.getAwsRegion()));
		
		String[] strZones = new String[zones.size()];
		for (int i = 0; i < zones.size(); i++) {
			strZones[i] = zones.get(i).getZone();
		}

		ArrayAdapter<String> ad = new ArrayAdapter<String>(
				getApplicationContext(),
				android.R.layout.simple_spinner_dropdown_item, strZones);

		final Spinner sp = (Spinner) dlg.findViewById(R.id.spZone);
		sp.setAdapter(ad);
		
		( (Button) dlg.findViewById(R.id.btnSave) ).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String availabilityZone = sp.getSelectedItem().toString();
				String size = ( (EditText) dlg.findViewById(R.id.etSize) ).getText().toString();
				
				try {
					new AmazonEc2().createVolume(size, availabilityZone);
					
					dlg.dismiss();
//					adapter.notifyDataSetChanged();
					
				} catch (AwsRequestException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	
		dlg.show();
	}
}
